/*
 *  Copyright (c) 2015 The CCP project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a Beijing Speedtong Information Technology Co.,Ltd license
 *  that can be found in the LICENSE file in the root of the web site.
 *
 *   http://www.yuntongxun.com
 *
 *  An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */
package com.fzsf.drawingboard.utils;

import android.os.Environment;
import android.text.TextUtils;

import com.fzsf.drawingboard.app.MyApplication;
import com.mauiie.aech.utils.LogUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 文件存取工具类
 * Created by TaiJL on 2015/3/17.
 */
public class FileAccessor {
    static String PERSONALIZEDFOLDER = "drawingBoard";

    public static final String APPS_ROOT_DIR = getExternalStorePath() + "/" + PERSONALIZEDFOLDER;
    public static final String IMESSAGE_VOICE = getExternalStorePath() + "/" + PERSONALIZEDFOLDER + "/voice";
    public static final String IMESSAGE_IMAGE = getExternalStorePath() + "/" + PERSONALIZEDFOLDER + "/image";
    public static final String IMESSAGE_AVATAR = getExternalStorePath() + "/" + PERSONALIZEDFOLDER + "/avatar";
    public static final String IMESSAGE_FILE = getExternalStorePath() + "/" + PERSONALIZEDFOLDER + "/file";

    /**
     * 初始化应用文件夹目录
     */
    public static void initFileAccess() {
        File rootDir = new File(APPS_ROOT_DIR);
        if (!rootDir.exists()) {
            rootDir.mkdir();
        }

        File imessageDir = new File(IMESSAGE_VOICE);
        if (!imessageDir.exists()) {
            imessageDir.mkdir();
        }

        File imageDir = new File(IMESSAGE_IMAGE);
        if (!imageDir.exists()) {
            imageDir.mkdir();
        }

        File fileDir = new File(IMESSAGE_FILE);
        if (!fileDir.exists()) {
            fileDir.mkdir();
        }
        File avatarDir = new File(IMESSAGE_AVATAR);
        if (!avatarDir.exists()) {
            avatarDir.mkdir();
        }
    }

    /**
     * 读取文件内容
     *
     * @param path 文件地址
     * @return 文件内容（String）
     */
    public static String readContentByFile(String path) {
        BufferedReader reader = null;
        String line = null;
        try {
            File file = new File(path);
            if (file.exists()) {
                StringBuilder sb = new StringBuilder();
                reader = new BufferedReader(new FileReader(file));
                while ((line = reader.readLine()) != null) {
                    sb.append(line.trim());
                }
                return sb.toString().trim();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }


    /**
     * 获取语音文件存储目录
     *
     * @return 语音文件存储目录
     */
    public static File getVoicePathName() {
        if (!isExistExternalStore()) {
            ToastUtil.showMessage("SD卡不存在");
            return null;
        }

        File directory = new File(IMESSAGE_VOICE);
        if (!directory.exists() && !directory.mkdirs()) {
            ToastUtil.showMessage("Path to file could not be created");
            return null;
        }

        return directory;
    }

    /**
     * 获取文件目录
     *
     * @return 文件存储目录
     */
    public static File getFilePathName() {
        if (!isExistExternalStore()) {
            ToastUtil.showMessage("SD卡不存在");
            return null;
        }

        File directory = new File(IMESSAGE_FILE);
        if (!directory.exists() && !directory.mkdirs()) {
            ToastUtil.showMessage("Path to file could not be created");
            return null;
        }

        return directory;
    }

    /**
     * 返回图片存放目录
     *
     * @return 图片存储目录
     */
    public static File getImagePathName() {
        if (!isExistExternalStore()) {
            ToastUtil.showMessage("SD卡不存在");
            return null;
        }

        File directory = new File(IMESSAGE_IMAGE);
        if (!directory.exists() && !directory.mkdirs()) {
            ToastUtil.showMessage("Path to file could not be created");
            return null;
        }

        return directory;
    }

    /**
     * 获取文件名
     *
     * @param pathName 根据文件路径获取文件名字
     * @return 文件名
     */
    public static String getFileName(String pathName) {

        int start = pathName.lastIndexOf("/");
        if (start != -1) {
            return pathName.substring(start + 1, pathName.length());
        }
        return pathName;

    }

    /**
     * 外置存储卡的路径
     *
     * @return
     */
    public static String getExternalStorePath() {
        if (isExistExternalStore()) {
            return Environment.getExternalStorageDirectory().getAbsolutePath();
        }
        return null;
    }

    /**
     * 是否有外存卡
     *
     * @return
     */
    public static boolean isExistExternalStore() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    /**
     * /data/data/packageName/files
     *
     * @return
     */
    public static String getAppContextPath() {

        if (null == MyApplication.getInstance()) {
            LogUtil.w("[ToastUtil] BaseApplication is null. \n\r" +
                    "+  you must extends BaseApplication if you want use this");
            return "";
        }

        return MyApplication.getInstance().getFilesDir().getAbsolutePath();
    }


    /**
     * 删除文件们
     *
     * @param filePaths 文件的绝对路径
     */
    public static void delFiles(ArrayList<String> filePaths) {
        for (String url : filePaths) {
            if (!TextUtils.isEmpty(url))
                delFile(url);
        }
    }

    /**
     * 删除单个文件
     *
     * @param filePath 文件的绝对路径
     * @return
     */
    public static boolean delFile(String filePath) {
        File file = new File(filePath);
        if (file == null || !file.exists()) {
            return true;
        }

        return file.delete();
    }

    /**
     * 重命名
     *
     * @param root     文件父目录
     * @param srcName  原名字
     * @param destName 新名字
     */
    public static void renameTo(String root, String srcName, String destName) {
        if (TextUtils.isEmpty(root) || TextUtils.isEmpty(srcName) || TextUtils.isEmpty(destName)) {
            return;
        }

        File srcFile = new File(root + srcName);
        File newPath = new File(root + destName);

        if (srcFile.exists()) {
            srcFile.renameTo(newPath);
        }
    }
}
